const redisClient = require("@/redis/redis-client");
const redisKeysConstant = require("@/constants/redis-keys.constant");
const fileBusinessService = require("@/common/file-business.service");
const BaseTaskScheduler = require("./base-task-scheduler");
const logger = require('$logger');

// cron规则, 每10分钟执行一次
const CRON_PATTERN = "*/10 * * * *";

// 数据库备份
const redisDeleteExpiredFamilyInviteCode = new BaseTaskScheduler();
/**
 * 任务运行
 */
const TaskHandler = async () => {
	try {
		logger.warning("定时任务执行中-删除Redis过期家庭邀请码");
		const keys = (await redisClient.get(redisKeysConstant.familyInvitationNumberKeys)) || [];
        const expiredKeys = [];
		for (let i = 0; i < keys.length; i++) {
			const key = redisKeysConstant.familyInvitationNumber(keys[i]);
			const itemData = await redisClient.get(key); // 在redis中查询文件过期信息
            if (!itemData) {
                expiredKeys.push(keys[i]);
            }
            if (itemData && itemData.expired_time && itemData.expired_time <= Date.now()) {
                await redisClient.del(key);
                expiredKeys.push(keys[i]);
                logger.success(`过期的家庭邀请码【${keys[i]}】删除成功`);
            }
		}

        // 如果删除了过期的key，同步key
        if (expiredKeys.length > 0) {
            const newInvitationNumberKeys = keys.filter(k => !expiredKeys.includes(k));
            await redisClient.set(redisKeysConstant.familyInvitationNumberKeys, newInvitationNumberKeys);
        }

	} catch (error) {
		logger.error("删除Redis过期家庭邀请码异常: " + error.message);
	}
};

// 创建一个30分钟执行一次的任务
redisDeleteExpiredFamilyInviteCode.createJob(CRON_PATTERN, TaskHandler, { initExecute: true });

module.exports = redisDeleteExpiredFamilyInviteCode;
